package com.powergisol.gis.timer;

import com.powergisol.gis.entity.TabYc;
import com.powergisol.gis.service.TabYcService;
import com.powergisol.gis.vo.DrillModel;
import com.powergisol.gis.vo.TabServiceVo;
import org.apache.poi.ss.formula.functions.T;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description:岩层生成进度查询
 */
//@Component
public class YcProgressTimer {

    @Autowired
    private TabYcService tabYcService;

    @Resource
    private CacheManager cacheManager;

    @Resource
    private RestTemplate restTemplate;

    @Value("${progress-url}")
    private String progressUrl;

    //第一次延迟1秒后执行，之后按fixedRate的规则每5秒执行一次
    @Scheduled(initialDelay = 1000, fixedRate = 2000)
    public void getYcProgress(){
        //查询正在生成岩层的岩层列表
        List<TabYc> listYc = tabYcService.getYcListState(0);
        for (TabYc tabYc:listYc) {
            System.out.println("定时器执行="+tabYc.getYcName());
            //查询缓存
            Cache cache = cacheManager.getCache("cache-data");
            if(null != cache.get(tabYc.getUuid())){
                Double ycProgres = cache.get(tabYc.getUuid(),Double.class);
                if(ycProgres == 100){
                    cache.put(tabYc.getUuid(),ycProgres);
                    continue;
                }
            }
            //调用接口
            try {
                ObjectMapper mapper = new ObjectMapper();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                DrillModel drillModel = new DrillModel();
                drillModel.setRequestGuid(tabYc.getUuid());
                HttpEntity<String> request = new HttpEntity<>(mapper.writeValueAsString(drillModel), headers);
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(progressUrl, request, String.class);
                String ycProgress = responseEntity.getBody();
                Double progress = Double.parseDouble(ycProgress);
                System.out.println(progress);
                cache.put(tabYc.getUuid(),progress);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
